<template>
  <view class="page">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="navbar-content">
        <view class="left-section" @tap="goBack">
          <image
            src="/static/icons/candidate/pre_page.png"
            class="back-icon"
            mode="aspectFit"
          ></image>
        </view>
        <text class="navbar-title">个人信息</text>
        <text class="save-btn" @tap="saveProfile">保存</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view class="content" scroll-y>
      <!-- 头像区域 -->
      <view class="section avatar-section">
        <text class="section-title">头像</text>
        <view class="avatar-wrapper" @tap="chooseAvatar">
          <image
            :src="formData.face || '/static/images/avatar.png'"
            class="avatar"
          ></image>
          <text class="avatar-tip">点击更换头像</text>
        </view>
      </view>

      <!-- 基本信息 -->
      <view class="section">
        <view class="form-item">
          <text class="label">称谓</text>
          <picker
            :range="sexOptions"
            :range-key="'label'"
            @change="onSexChange"
            class="picker"
          >
            <view class="picker-content">
              <text :class="['value', formData.sex ? '' : 'placeholder']">
                {{ sexText || "暂未设置" }}
              </text>
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">昵称</text>
          <input
            v-model="formData.nickname"
            placeholder="请输入昵称"
            class="input"
            maxlength="20"
          />
        </view>

        <view class="form-item">
          <text class="label">真实姓名</text>
          <input
            v-model="formData.realName"
            placeholder="请输入真实姓名"
            class="input"
            maxlength="10"
          />
        </view>

        <view class="form-item">
          <text class="label">生日</text>
          <picker mode="date" @change="onBirthdayChange" class="picker">
            <view class="picker-content">
              <text :class="['value', formData.birthday ? '' : 'placeholder']">
                {{ formData.birthday || "暂未设置" }}
              </text>
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">毕业年份</text>
          <picker
            :range="yearOptions"
            :range-key="'label'"
            @change="onGraduationYearChange"
            class="picker"
          >
            <view class="picker-content">
              <text :class="['value', formData.graduationYear ? '' : 'placeholder']">
                {{ graduationYearText || "暂未设置" }}
              </text>
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </picker>
        </view>
      </view>

      <!-- 联系信息 -->
      <view class="section">
        <view class="form-item">
          <text class="label">手机号</text>
          <view class="phone-wrapper">
            <text class="phone-text">{{ formData.phone || "暂未设置" }}</text>
            <text class="phone-tip">如需修改请联系客服</text>
          </view>
        </view>

        <view class="form-item">
          <text class="label">邮箱</text>
          <input
            v-model="formData.email"
            placeholder="请输入邮箱地址"
            class="input"
            type="email"
          />
        </view>

     
      </view>

      <!-- 工作信息 -->
      <!-- <view class="section">
        <view class="form-item">
          <text class="label">参加工作时间</text>
          <picker mode="date" @change="onWorkDateChange" class="picker">
            <view class="picker-content">
              <text
                :class="['value', formData.startWorkDate ? '' : 'placeholder']"
              >
                {{ formData.startWorkDate || "暂未设置" }}
              </text>
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </picker>
        </view>
      </view> -->
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useUserStore } from "@/stores/modules/user";
import { modifyUserInfoApi, getAvatarUploadSignApi } from "@/api/user";
import { chooseFile, uploadFile2OSS } from "@/utils/file.js";
import { updateAvatarApi } from "../../api/user";
import { showSeccessToast } from "../../utils/toast";
const userStore = useUserStore();

// 性别选项
const sexOptions = [
  { value: 1, label: "男" },
  { value: 2, label: "女" },
  { value: 3, label: "保密" },
];

// 生成年份选项（从1970年到当前年份+2年）
const generateYearOptions = () => {
  const currentYear = new Date().getFullYear();
  const years = [];
  for (let year = currentYear + 2; year >= 1970; year--) {
    years.push({ value: year, label: `${year}年` });
  }
  return years;
};

const yearOptions = generateYearOptions();

// 表单数据
const formData = ref({
  face: "",
  sex: 3,
  nickname: "",
  realName: "",
  birthday: "",
  phone: "",
  email: "",
  startWorkDate: "",
  position: "",
  graduationYear: "",
});

// 计算属性：性别文本
const sexText = computed(() => {
  const sexOption = sexOptions.find(
    (item) => item.value === formData.value.sex
  );
  return sexOption ? sexOption.label : "";
});

// 计算属性：毕业年份文本
const graduationYearText = computed(() => {
  const yearOption = yearOptions.find(
    (item) => item.value === formData.value.graduationYear
  );
  return yearOption ? yearOption.label : "";
});

// 初始化数据
const initFormData = () => {
  const userInfo = userStore.userInfo;
  if (userInfo) {
    formData.value = {
      face: userInfo.face || "",
      sex: userInfo.sex || 3,
      nickname: userInfo.nickName || userInfo.nickname || "",
      realName: userInfo.realName || "",
      birthday: userInfo.birthday || "",
      phone: userInfo.phone || "",
      email: userInfo.email || "",
      startWorkDate: userInfo.startWorkDate || "",
      position: userInfo.position || "",
      graduationYear: userInfo.graduationYear || "",
    };
  }
};

// 事件处理
const onSexChange = (e) => {
  const index = parseInt(e.detail.value);
  formData.value.sex = sexOptions[index].value;
};

const onBirthdayChange = (e) => {
  formData.value.birthday = e.detail.value;
};

const onWorkDateChange = (e) => {
  formData.value.startWorkDate = e.detail.value;
};

const onGraduationYearChange = (e) => {
  const index = parseInt(e.detail.value);
  formData.value.graduationYear = yearOptions[index].value;
};

const goBack = () => {
  // 返回mine页面
  uni.redirectTo({
    url: "/pages/candidate/mine",
  });
};
// 选择头像
const chooseAvatar = async () => {
  const tempFilePath = await chooseFile({
    count: 1,
    mediaType: ["image"],
    sourceType: ["album", "camera"],
  });
  if (!tempFilePath) {
    return;
  }
  try {
    uni.showLoading({ title: "上传中..." });
    const tempAvatar = await uploadFile2OSS(
      tempFilePath,
      "avatar",
      getAvatarUploadSignApi
    );
    await updateAvatarApi(tempAvatar);
    await userStore.getUserInfoAction();
    uni.hideLoading();
    showSeccessToast("更新成功");
  } catch (e) {
    uni.hideLoading();
    uni.showToast({
      title: "头像上传失败",
      icon: "none",
    });
  }
};

const formatDate = (dateStr) => {
  if (!dateStr) return "";
  return dateStr;
};

const saveProfile = async () => {
  try {
    uni.showLoading({
      title: "保存中...",
      mask: true,
    });

    // 构建提交数据
    const submitData = {
      userId: userStore.userInfo.id,
      face: formData.value.face,
      sex: formData.value.sex,
      nickName: formData.value.nickname,
      realName: formData.value.realName,
      birthday: formatDate(formData.value.birthday),
      email: formData.value.email,
      startWorkDate: formatDate(formData.value.startWorkDate),
      position: formData.value.position,
      graduationYear: formData.value.graduationYear,
    };

    // 调用API保存用户信息
    await modifyUserInfoApi(submitData);

    // 更新本地存储 - 使用getUserInfoAction刷新最新数据
    await userStore.getUserInfoAction();
    uni.hideLoading();
    uni.showToast({
      title: "保存成功",
      icon: "success",
    });
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || "保存失败，请重试",
      icon: "none",
    });
  }
};

// 监听userStore.userInfo变化，实时同步数据
watch(
  () => userStore.userInfo,
  (newUserInfo) => {
    if (newUserInfo) {
      initFormData();
    }
  },
  { deep: true }
);

onMounted(() => {
  initFormData();
});
</script>

<style scoped>
.page {
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
  min-height: 100vh;
}

/* 导航栏 */
.navbar {
  background-color: #fff;
  border-bottom: 1rpx solid #e6e6e6;
  /* 适配安全区域 */
  padding-top: var(--status-bar-height);
}

.navbar-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  height: 88rpx;
  position: relative;
}

.left-section {
  display: flex;
  align-items: center;
  min-width: 80rpx;
  padding: 20rpx 0;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
  display: block;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.save-btn {
  font-size: 32rpx;
  color: #00bdb4;
  z-index: 10;
  min-width: 80rpx;
  text-align: right;
}

/* 内容区域 */
.content {
  flex: 1;
  padding: 20rpx 0;
}

.section {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 0 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 30rpx;
  display: block;
}

.avatar-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 40rpx 30rpx;
}

.avatar-wrapper {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-radius: 10rpx;
  transition: background-color 0.2s;
}

.avatar-wrapper:active {
  background-color: #f5f5f5;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.avatar-tip {
  font-size: 28rpx;
  color: #999;
}

.form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.form-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 32rpx;
  color: #333;
  width: 200rpx;
}

.input {
  flex: 1;
  font-size: 32rpx;
  color: #333;
  text-align: right;
}

.picker {
  flex: 1;
}

.picker-content {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.value {
  font-size: 32rpx;
  color: #333;
}

.placeholder {
  color: #999;
}

.arrow-icon {
  width: 24rpx;
  height: 24rpx;
  margin-left: 10rpx;
}

.phone-wrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.phone-text {
  font-size: 32rpx;
  color: #333;
}

.phone-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 5rpx;
}
</style>